package com.daiTest.interceptors;

import com.daiTest.untils.JwtHelper;
import com.daiTest.untils.Result;
import com.daiTest.untils.ResultCodeEnum;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.ParameterResolutionDelegate;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.servlet.HandlerInterceptor;

/*
 * description：登录保护拦截器 检查请求头是否包含有效token
 * 有放行
 * 没有 无效 504*/
@Component
public class LoginProtectedlnterceptor implements HandlerInterceptor {

    @Autowired
    private JwtHelper jwtHelper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //从请求头中获取token
        String token = request.getHeader("token");
        //检查token是否过期
        boolean expiration = jwtHelper.isExpiration(token);
        //有效放行
        if(!expiration){
            return true;
        };
        // 无效返回504状态json 只能自己用响应对象返回状态了
        Result result = Result.build(null, ResultCodeEnum.NOTLOGIN);
        ObjectMapper objectMapper=new ObjectMapper();
        String json = objectMapper.writeValueAsString(result);
        response.getWriter().print(json);
        return false;

    }
}
